from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from private_website.apps.app01 import models
from tools.const import BASE_DIR
from tools.tools import get_pic_name
from tools.const import folders
import os


class UserSer(serializers.Serializer):
    username = serializers.CharField(min_length=2, max_length=10,
                                     error_messages={
                                         'min_length': '用户名不能少于两个字符',
                                         'max_length': '用户名不可以长于十个字符·',
                                         'blank': ' 用户名不能为空'
                                     }
                                     )
    password = serializers.CharField(min_length=3, max_length=20,
                                     error_messages={
                                         'min_length': '密码不可短于3个字符',
                                         'max_length': '密码不可长于20个字符',
                                         'blank': '密码不能为空'
                                     }
                                     )
    phone = serializers.CharField(error_messages={'blank': '电话号码不能为空'})
    avatar = serializers.FileField(allow_null=True, allow_empty_file=True)

    def create(self, validated_data):
        file = validated_data.get('avatar')
        username = validated_data.get('username')
        p = '/static/' + username + '/'
        if not os.path.exists(BASE_DIR + p):
            os.mkdir(BASE_DIR + p)
            for i in folders:
                os.mkdir(BASE_DIR + p + i)
        if not file:
            p = '/static/avatar.jpeg'
        else:
            p = p + 'avatar/' + get_pic_name(file.name)
            path = BASE_DIR + p
            with open(path, 'wb') as f:
                for contend in file.chunks():
                    f.write(contend)
        validated_data['avatar'] = p
        obj = models.Users.objects.create(**validated_data)
        # obj = models.Users.objects.first()
        return obj

    def validate_username(self, data):
        if models.Users.objects.filter(username=data):
            raise ValidationError('该用户名已存在')
        return data

    def validate_phone(self, data):
        if len(data) != 11:
            raise ValidationError('手机号码格式不正确')
        if models.Users.objects.filter(phone=data):
            raise ValidationError('该手机号已经注册')
        return data

    def validated_password(self, data):
        if models.Users.objects.filter(password=data):
            raise ValidationError('此号码已注册')
        return data


class UserInfoSer(serializers.ModelSerializer):
    class Meta:
        model = models.Users
        fields = [
            'username', 'phone', 'avatar', 'mail', 'remark'
        ]
